<?php
/**
 * mae. database support
 * based on ADOdb
 */
require_once('internal/adodb/adodb-exceptions.inc.php');
require_once('internal/adodb/adodb.inc.php');
require_once('internal/adodb/adodb-active-record.inc.php');
require_once('internal/adodb/adodb-error.inc.php');


class Database {
	public $affected_rows, $num_rows;

	function __construct($type, $server, $user, $pass, $database) {
		global $mae;
		$this->cache = $mae['site_cache'];
		$GLOBALS['ADODB_CACHE_DIR'] = $mae['site_cachedir'];

		try {
			$this->db = ADONewConnection($type);
			$this->db->PConnect($server, $user, $pass, $database);
			if ($this->cache) $this->db->cacheSecs = $mae['site_cachetime'];
		} catch (Exception $e) {
			error('db_con');
		}
	}

	function __destruct() {
		return $this->db->close();
	}

	public function query($que) {
		if ($this->cache) $q = $this->db->cacheExecute($que);
		else $q = $this->db->execute($que);

		$this->affected_rows = $this->db->affected_rows();
		if (strpos(strtolower($que), 'select') === 0) $this->num_rows = $q->recordCount();

		return $q;
	}

	public function modeAssoc() { $this->db->setFetchMode(ADODB_FETCH_ASSOC); }
	public function modeNum() { $this->db->setFetchMode(ADODB_FETCH_NUM); }
	public function error() { return $this->db->errorMsg(); }

	public function select($database, $what='*', $where=array()) {
		global $mae;
		$wheres = (count($where)==0) ? '' : ' WHERE '.implode(', ', $where);
		return $this->query("SELECT $what FROM {$mae[db_prefix]}$database$wheres;");
	}
	public function selectLimit($sql, $numrows=-1, $offset=-1, $inputarr=false) {
		if ($this->cache) return $this->db->cacheSelectLimit($sql, $numrows, $offset, $inputarr);
		return $this->db->selectLimit($sql, $numrows, $offset, $inputarr);
	}
}
?>
